const app = getApp();
const api = app.globalData.api;
Page({
    data: {
        did: 0,//动态id
        userInfo: {},//当前用户信息
        dynamicInner: {},//动态详情
        isCommentVisable: true,//评论区是否展开
        FComment: '',//主评论
    },

    onLoad: function (options) {
        this.setData({
            'did': options.id,
            // 'did': 4,
            'userInfo': wx.getStorageSync('loginUser')
        });
        console.log(this.data.did);
        setTimeout(() => {
            this.getDynamicInner();
        }, 200);
    },

    inputComment(e) {
        console.log(e.detail.value);
        this.setData({
            'FComment': e.detail.value
        });
    },

    commentSubmit() {
        let that = this;
        if (!this.data.FComment) {
            wx.showToast({
                title: '评论不为为空',
                icon: 'error',
            });
        } else {
            wx.request({
                url: api + '/public/addNewComment',
                method: 'POST',
                data: {
                    postId: -1,
                    dynamicId: that.data.dynamicInner.dynamic.id,
                    authorId: that.data.userInfo.id,
                    username: that.data.userInfo.username,
                    avatar: that.data.userInfo.avatar,
                    content: that.data.FComment,
                },
                success(res) {
                    console.log(res.data);
                    if (res.data.code == 200) {
                        wx.showToast({
                            title: '评论成功',
                            icon: 'success'
                        });
                        that.getDynamicInner();//重新获取内容
                    } else {
                        wx.showToast({
                            title: '回复评论失败',
                            icon: 'none'
                        });
                    }
                },
                fail(err) {
                    console.log(err);
                    wx.showToast({
                        title: '发起评论请求失败',
                        icon: 'none'
                    })
                }
            });
        }
    },

    //关闭和开启评论区
    commentDynamic(){
        let is = this.data.isCommentVisable;
        this.setData({
            'isCommentVisable': !is
        });
    },

    //删除动态
    deleteDynamic(e) {
        let dynamicId = e.currentTarget.dataset.did;//要删除的动态id
        wx.showModal({
            'title': '确定要删除此动态吗？',
            confirmText: '确定',
            complete: (result) => {
                if (result.confirm) {
                    console.log("用户点击了确定");
                    wx.request({
                        url: api + '/user/delDynamic/' + dynamicId,
                        method: 'POST',
                        success: (res) => {
                            console.log(res.data);
                            if (res.data.code == 200) {//删除成功
                                wx.switchTab({//跳转到翻译圈子页面
                                    url: '/pages/translationCircle/translationCircle',
                                });
                            } else {
                                wx.showToast({
                                    title: '动态删除失败',
                                    icon: 'none'
                                })
                            }
                        },
                        fail: (err) => {
                            console.log(err);
                            wx.showToast({
                                title: '删除请求发送失败',
                                icon: 'none'
                            })
                        }
                    });
                }
            },
        })

    },

    //删除评论
    deleteComment(e) {
        let commentId = e.currentTarget.dataset.cid;//要删除的评论id
        wx.request({
            url: api + '/public/delComment/' + commentId,
            method: 'POST',
            success: (res) => {
                console.log(res.data);
                if (res.data.code == 200) {//删除成功
                    this.getDynamicInner();//重新获取动态内部信息
                } else {
                    wx.showToast({
                        title: '评论删除失败',
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                console.log(err);
                wx.showToast({
                    title: '删除请求发送失败',
                    icon: 'none'
                })
            }
        });
    },

    //获取动态内部信息，包括评论
    getDynamicInner() {
        let that = this;
        wx.request({
            url: api + '/user/getDynamicInner/' + that.data.did,
            method: 'GET',
            success: (res) => {
                console.log(res.data);
                if (res.data.code == 200) {
                    that.setData({
                        'dynamicInner': res.data.data
                    });
                    that.addIsLikeThumb();//增加两个字段，当前用户是否喜欢了，是否点赞了
                    that.formatDate();//修改时间格式
                } else {
                    wx.showToast({
                        title: '动态信息获取失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.log(err);
                wx.showToast({
                    title: '动态获取请求失败',
                    icon: 'none'
                });
            }
        });
    },

    //增加两个字段，当前用户是否喜欢了，是否点赞了
    addIsLikeThumb() {
        let temp = this.data.dynamicInner.dynamic;
        let isLike = false;
        let isThumb = false;
        let likeList = temp.likeList.split(",").filter(function (item) {
            return item !== '';
        });
        let thumbList = temp.thumbList.split(",").filter(function (item) {
            return item !== '';
        });

        if (likeList.indexOf(String(this.data.userInfo.id)) != -1) {
            isLike = true;
        }
        if (thumbList.indexOf(String(this.data.userInfo.id)) != -1) {
            isThumb = true;
        }
        temp.isLike = isLike;
        temp.isThumb = isThumb;
        this.setData({
            'dynamicInner.dynamic': temp
        });
        console.log(this.data.dynamicInner.dynamic);
    },

    //修改时间格式
    formatDate() {
        let commentList = this.data.dynamicInner.commentList;
        let dynamic = this.data.dynamicInner.dynamic;
        commentList.forEach(element => {
            // 创建一个 Date 对象
            const date = new Date(element.createTime);
            // 获取年、月、日等信息
            const year = date.getFullYear();
            const month = date.getMonth() + 1; // 月份是从 0 开始计数的，需要加 1
            const day = date.getDate();
            const hours = date.getHours();
            const minutes = date.getMinutes();
            const seconds = date.getSeconds();
            // 格式化时间字符串
            // const formattedDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
            const formattedDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
            element.createTime = formattedDate;
        });
        // 创建一个 Date 对象
        const date = new Date(dynamic.createTime);
        // 获取年、月、日等信息
        const year = date.getFullYear();
        const month = date.getMonth() + 1; // 月份是从 0 开始计数的，需要加 1
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        // 格式化时间字符串
        const formattedDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hours}:${minutes < 10 ? '0' + minutes : minutes}`;
        dynamic.createTime = formattedDate;
        this.setData({
            'dynamicInner.commentList': commentList,
            'dynamicInner.dynamic': dynamic,
        });
    },

    reply(e) {
        let username = e.currentTarget.dataset.username;
        let postId = e.currentTarget.dataset.cid;
        let that = this;
        wx.showModal({
            title: '你正在回复@' + username,
            editable: true, // 可输入
            content: '',
            complete: (res) => {
                if (res.confirm) {
                    if (!res.content) { // 输入的值
                        wx.showToast({
                            title: '输入为空，回复失败',
                            icon: 'none'
                        })
                    } else {
                        // 调接口
                        console.log("回复的内容为", res.content);
                        wx.request({
                            url: api + '/public/addNewComment',
                            method: 'POST',
                            data: {
                                postId: postId,
                                dynamicId: that.data.dynamicInner.dynamic.id,
                                authorId: that.data.userInfo.id,
                                username: that.data.userInfo.username,
                                avatar: that.data.userInfo.avatar,
                                content: res.content,
                            },
                            success(ress) {
                                console.log(ress.data);
                                if (ress.data.code == 200) {
                                    that.getDynamicInner();//重新获取内容
                                } else {
                                    wx.showToast({
                                        title: '回复评论失败',
                                        icon: 'none'
                                    });
                                }
                            },
                            fail(err) {
                                console.log(err);
                                wx.showToast({
                                    title: '发起评论请求失败',
                                    icon: 'none'
                                })
                            }
                        });
                    }
                }
            }
        });

    },

    likeDynamic: function () {
        // 喜欢动态逻辑
        console.log('喜欢动态');
        let id = this.data.did;
        console.log(id);
        let curDynamic = this.data.dynamicInner.dynamic;
        let url = '';
        console.log("当前动态==>", curDynamic.isLike);
        if (!curDynamic.isLike) {
            url = '/user/likeDynamic/';
        } else {
            url = '/user/CancelLikeDynamic/';
        }
        console.log("url==>", url);
        let that = this;
        setTimeout(() => {
            wx.request({
                url: api + url + id + '/' + that.data.userInfo.id,
                method: 'POST',
                success: (res) => {
                    console.log(res.data);
                    if (res.data.code == 200) {
                        let tempD = that.data.dynamicInner.dynamic;
                        if (id == tempD.id) {
                            tempD.isLike = !tempD.isLike;
                            tempD.likeNum = res.data.data.likeNum;
                        }
                        that.setData({
                            'dynamicInner.dynamic': tempD
                        });
                    } else {
                        wx.showToast({
                            title: '操作失败，出现异常',
                            icon: 'none'
                        })
                    }
                },
                fail: (err) => {
                    console.log(err);
                    wx.showToast({
                        title: '操作失败，网络异常',
                        icon: 'none'
                    })
                }
            })
        }, 200);
    },

    dianzanDynamic: function (e) {
        // 点赞动态逻辑
        console.log('点赞动态');
        let id = this.data.did;
        console.log(id);
        let curDynamic = this.data.dynamicInner.dynamic;
        let url = '';
        console.log("当前动态==>", curDynamic.isThumb);
        if (!curDynamic.isThumb) {
            url = '/user/thumbDynamic/';
        } else {
            url = '/user/CancelThumbDynamic/';
        }
        console.log("url==>", url);
        let that = this;
        setTimeout(() => {
            wx.request({
                url: api + url + id + '/' + that.data.userInfo.id,
                method: 'POST',
                success: (res) => {
                    console.log(res.data);
                    if (res.data.code == 200) {
                        let tempD = that.data.dynamicInner.dynamic;
                        if (id == tempD.id) {
                            tempD.isThumb = !tempD.isThumb;
                            tempD.thumbNum = res.data.data.thumbNum;
                        }
                        that.setData({
                            'dynamicInner.dynamic': tempD
                        });
                    } else {
                        wx.showToast({
                            title: '操作失败，出现异常',
                            icon: 'none'
                        })
                    }
                },
                fail: (err) => {
                    console.log(err);
                    wx.showToast({
                        title: '操作失败，网络异常',
                        icon: 'none'
                    })
                }
            })
        }, 200);
    },
})